﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PerfumeShopManagement.DAL;
using PerfumeShopManagement.Model;
using System.Data.Linq;
using PerfumeShopManagement.Utility;

namespace PerfumeShopManagement.BLL
{
    public class BllImportCheck : BllAbstractBase<ImportCheck, int>
    {
        public BllImportCheck() 
            : base()
        {
            items = DalFactory.ImportCheckDAL.GetAllObjects();
        }

        public override List<ImportCheck> GetAll()
        {
            return items;
        }

        public override ImportCheck Get(int id)
        {
            foreach (ImportCheck importCheck in items)
            {
                if (importCheck.ImportCheckId == id)
                {
                    return importCheck;
                }
            }

            return null;
        }

        public override List<ImportCheck> Search(ImportCheck criteria)
        {
            throw new NotImplementedException();
        }

        public override bool Save(ImportCheck obj)
        {
            ImportCheck importCheck = obj;

            bool updated = false;
            foreach (ImportCheck item in items)
            {
                if (item.ImportCheckId == importCheck.ImportCheckId)
                {
                    item.ImportCheckTime = importCheck.ImportCheckTime;
                    item.ImportCheckDetail = importCheck.ImportCheckDetail;
                    item.Total = importCheck.Total;
                    updated = true;
                    DalFactory.ImportCheckDAL.Update(importCheck);

                    return true;
                }
            }

            if (!updated)
            {
                items.Add(importCheck);

                foreach (ImportCheckDetail detail in importCheck.ImportCheckDetail)
                {
                    Product product = DalFactory.ProductDAL.GetObjectById(detail.ProductId);
                    product.Inventory += detail.ImportCheckAmount;
                    DalFactory.ProductDAL.Update(product);

                    RepositoryHistory history = new RepositoryHistory();
                    history.ProductId = detail.ProductId;
                    history.ActivityKind = Constants.IMPORT_KIND;
                    history.ActiveTime = DateTime.Now;
                    history.Value = detail.ImportCheckAmount;
                    DalFactory.RepositoryHistoryDAL.Insert(history);
                }

                DalFactory.ImportCheckDAL.Insert(importCheck);
                return true;
            }

            return false;
        }

        public override bool DeleteById(int id)
        {
            throw new NotImplementedException();
        }
    }
}
